package com.example.weatherapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.weatherapp.databinding.ActivityWeatherBinding;
import com.example.weatherapp.gson.AQI;
import com.example.weatherapp.gson.BingPic;
import com.example.weatherapp.gson.Forecast;
import com.example.weatherapp.gson.NowWeather;
import com.example.weatherapp.gson.Suggest;
import com.example.weatherapp.gson.TotalWeather;
import com.example.weatherapp.util.HttpUtil;
import com.example.weatherapp.util.Utility;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Text;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    public static final String FORECAST_URL="https://pn2tumybjj.re.qweatherapi.com/v7/weather/7d";
    public static final String AQI_URL="https://pn2tumybjj.re.qweatherapi.com/v7/air/now";
    public static final String SUGGEST_URL="https://pn2tumybjj.re.qweatherapi.com/v7/indices/1d";
    public static final String NOWEATGER_URL="https://pn2tumybjj.re.qweatherapi.com/v7/weather/now";
    public static final String KEY="9c64a7e742724fa9b2078ec43615c8c1";
    private String current_province;
    private String current_city;
    private String current_county;
    private String type="1,3,8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loadBingPic();
        SharedPreferences sp = getSharedPreferences("weather",MODE_PRIVATE);
        String location= sp.getString("location","");
        String json=sp.getString("weather","");
        String updateTime=sp.getString("updateTime","");
        if (!TextUtils.isEmpty(json)){
            Gson gson= new Gson();
            TotalWeather totalWeather = gson.fromJson(json, TotalWeather.class);
            showNowWeatherInfo(totalWeather.getNowWeather());
            showForecastInfo(totalWeather.getForecast());
            showAQIInfo(totalWeather.getAqi());
            showSuggestInfo(totalWeather.getSuggest());
            binding.includeTitle.titleCity.setText(location);
            binding.includeTitle.titleUpdateTime.setText(updateTime);
            return;
        }

        Intent intent=getIntent();
        String weatherId = intent.getStringExtra("weather_id");
        current_province=intent.getStringExtra(" current_province");
        current_city=intent.getStringExtra("current_city");
        current_county=intent.getStringExtra("current_county");

        binding.includeTitle.titleCity.setText(String.format("%s %s %s",current_province,current_city,current_county));
        weatherId=weatherId.substring(2);
        requestWeather(weatherId);

    }
    private void loadBingPic(){
        String url="http://api.xygeng.cn/openapi/bing";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this,"获取Bing每日图片失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                BingPic bingPic =new Gson().fromJson(result,BingPic.class);
                Log.d("TAG123",result);
                runOnUiThread(()->{
                    if (bingPic!=null&&bingPic.getCode()==200){
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    }else{
                        Toast.makeText(WeatherActivity.this,"获取Bing每日图片失败",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    public void requestWeather(String location){
        loadBingPic();
        String url0 = NOWEATGER_URL + "?" + "location=" +location + "&key=" +KEY;
        String url1 = FORECAST_URL + "?" + "location=" +location + "&key=" +KEY;
        String url2 = AQI_URL + "?" + "location=" +location + "&key=" +KEY;
        String url3 = SUGGEST_URL + "?" + "location=" +location + "&key=" +KEY + "&type=" + type;

        Gson gson=new Gson();
        Observable<Response> observable0= HttpUtil.request(url0);
        Observable<Response> observable1= HttpUtil.request(url1);
        Observable<Response> observable2= HttpUtil.request(url2);
        Observable<Response> observable3= HttpUtil.request(url3);
        Observable.zip(
                observable0,
                observable1,
                observable2,
                observable3,
                (response0, response1, response2, response3) -> {
                    try {
                        NowWeather nowWeather =gson.fromJson(response0.body().string(),NowWeather.class);
                        Forecast forecast = gson.fromJson(response1.body().string(),Forecast.class);
                        AQI aqi= gson.fromJson(response2.body().string(),AQI.class);
                        Suggest suggest = gson.fromJson(response3.body().string(),Suggest.class);

                        TotalWeather totalWeather=new TotalWeather();
                        totalWeather.setNowWeather(nowWeather);
                        totalWeather.setAqi(aqi);
                        totalWeather.setForecast(forecast);
                        totalWeather.setSuggest(suggest);

                        String toWrite = gson.toJson(totalWeather);
                        SharedPreferences sp = getSharedPreferences("weathetr", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("weather",toWrite);
                        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        editor.putString("updateTime",sf.format(new Date()));
                        editor.putString("Location",String.format("%s %s %s",current_province,current_city,current_county));
                        editor.apply();


                        return new Object[]{nowWeather,forecast,aqi,suggest};
                    }finally {
                        response1.close();
                        response2.close();
                        response3.close();
                    }
                }
        ).observeOn(AndroidSchedulers.mainThread()).
                subscribe(
                        results ->{
                            showNowWeatherInfo((NowWeather)results[0]);
                            showForecastInfo((Forecast) results[1]);
                            showAQIInfo((AQI) results[2]);
                            showSuggestInfo((Suggest) results[3]);
                        },
                        throwable -> {
                            Toast.makeText(this,"访问网络操作出错！",Toast.LENGTH_SHORT).show();
                        }
                );
    }
    private void showNowWeatherInfo(NowWeather nowWeather){

        if (nowWeather!=null&&nowWeather.getCode().equals("200")){
            String temp = nowWeather.getNow().getTemp();
            binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
            binding.includeNow.degreeText.setText(String.format("%s ℃",
                    temp));
        }else {
            Toast.makeText(this,"获取实时天气信息出错！",Toast.LENGTH_SHORT).show();
        }

    }
    private void showSuggestInfo(Suggest suggest){

        if (suggest!=null && suggest.getCode().equals("200")){
            binding.includeSuggestion.comfortText.setText(String.format("舒适度指数： \n %s \n %s",
                    suggest.getDaily().get(2).getCategory(),
                    suggest.getDaily().get(2).getText()));
            binding.includeSuggestion.sportText.setText(String.format("运动指数： \n %s \n %s",
                    suggest.getDaily().get(0).getCategory(),
                    suggest.getDaily().get(0).getText()));
            binding.includeSuggestion.wearText.setText(String.format("穿衣指数： \n %s \n %s",
                    suggest.getDaily().get(1).getCategory(),
                    suggest.getDaily().get(1).getText()));
        }else{
            Toast.makeText(this,"获取天气指数出错！",Toast.LENGTH_SHORT).show();
        }

    }

    private void showAQIInfo(AQI aqi){

        if (aqi!=null && aqi.getCode().equals("200")){
            binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
            binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
        }else {
            Toast.makeText(this,"获取实时空气质量出错！",Toast.LENGTH_SHORT).show();
        }

    }

    private void showForecastInfo(Forecast forecast){

        if (forecast!=null && forecast.getCode().equals("200")){
            binding.includeForecast.forecastLayout.removeAllViews();
            for (Forecast.DailyDTO dailyDTO : forecast.getDaily()){
                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                        binding.includeForecast.forecastLayout,false);
                TextView dateText = (TextView) view.findViewById(R.id.date_text);
                TextView infoText = (TextView) view.findViewById(R.id.info_text);
                TextView maxText = (TextView) view.findViewById(R.id.max_text);
                TextView minText = (TextView) view.findViewById(R.id.min_text);
                dateText.setText(dailyDTO.getFxDate());
                infoText.setText(dailyDTO.getTextDay());
                maxText.setText(dailyDTO.getTempMax());
                minText.setText(dailyDTO.getTempMin());
                binding.includeForecast.forecastLayout.addView(view);
            }
        }else{
            Toast.makeText(this,"获取未来7天天气预报出错！",Toast.LENGTH_SHORT).show();
        }

    }
}